package com.sherlocky.document.initializer;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.ApplicationContextInitializer;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.annotation.Order;
import org.springframework.core.env.Environment;

/**
 * 自定义初始化器校验配置项
 */
@Slf4j
@Order(1)
public class DocumentApiContextInitializer implements ApplicationContextInitializer {
    @Override
    public void initialize(ConfigurableApplicationContext applicationContext) {
        Environment env = applicationContext.getEnvironment();
        String documentServerHost = env.getProperty("document.server.host");
        String onlyofficeDocumentServerHost = env.getProperty("onlyoffice.document-server.host");
        String onlyofficeDocumentServerJsAPI = env.getProperty("onlyoffice.document-server.api.js");
        String fileSizeLimit = env.getProperty("document.file-size.limit");
        if (StringUtils.isEmpty(documentServerHost)) {
            throw new RuntimeException("启动失败！缺少配置：document.server.host");
        } else if (StringUtils.isEmpty(onlyofficeDocumentServerHost)) {
            throw new RuntimeException("启动失败！缺少配置：onlyoffice.document-server.host");
        } else if (StringUtils.isEmpty(onlyofficeDocumentServerJsAPI)) {
            throw new RuntimeException("启动失败！缺少配置：onlyoffice.document-server.api.js");
        } else if (fileSizeLimit != null && StringUtils.isNumeric(fileSizeLimit)) {
            // 不为null但配置了空值--空(白)字符串的情况，springboot无法将值转为Long
            throw new RuntimeException("启动失败！错误配置：document.file-size.limit，必须为整数!");
        }
    }
}
